using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Runtime.Remoting.Messaging;
using Spring.Context.Support;
using IBatisNet.DataMapper;
using IBatisNet.DataMapper.Configuration;
using Com.Pirate.Common.Contexts.Utils;

namespace Com.Pirate.Common.Contexts
{
    public class IbatisSqlMapContext
    {
        static IbatisSqlMapContext _context;

        public ISqlMapper GetSqlMapper()
        {

            var mapper = (ISqlMapper)CallContext.GetData("MAPPER");
            if (mapper == null)
            {
                var appContext = new XmlApplicationContext(@"Resources\SpringNet.config");
                mapper = (ISqlMapper)appContext.GetObject("ProjectSqlMapper");
                CallContext.SetData("MAPPER", mapper);
            }
            else
                mapper = (ISqlMapper)CallContext.GetData("MAPPER");
            return mapper;
        }

        public ISqlMapper GetSqlMapper(string databaseName)
        {
            var mapper = (ISqlMapper)CallContext.GetData(databaseName);
            if (mapper == null)
            {
                DomSqlMapBuilder builder = new DomSqlMapBuilder();
                XmlDocument doc = new XmlDocument();
                doc.Load(FrameworkConfigInfo.GetIbatisSqlMapperFilePath(databaseName));
                mapper= builder.Build(doc, false);
                CallContext.SetData(databaseName, mapper);
            }
            else
                mapper = (ISqlMapper)CallContext.GetData(databaseName);
            return mapper;
        }

        public ISqlMapper GetProjectsSqlMapper()
        {
            return GetSqlMapper("projects");
        }

        //public ISqlMapper GetBasicSqlMapper()
        //{

        //    var mapper = (ISqlMapper)CallContext.GetData("BASICMAPPER");
        //    if (mapper == null)
        //    {
        //        DomSqlMapBuilder builder = new DomSqlMapBuilder();
        //        XmlDocument doc = new XmlDocument();
        //        doc.Load(@"Resources\DatabaseSchemaSqlMapper.Config");
        //        mapper = builder.Build(doc, false);
        //        CallContext.SetData("BASICMAPPER", mapper);
        //    }
        //    else
        //        mapper = (ISqlMapper)CallContext.GetData("BASICMAPPER");
        //    return mapper;

        //}

        public static IbatisSqlMapContext Context
        {
            get
            {
                if (_context == null)
                    _context = new IbatisSqlMapContext();
                return _context;
            }
        }
    }
}
